module.exports = app => {
    const express = require("express")
    const jwt = require('jsonwebtoken');
    const model = require('../../models/AdminUser');
    const assert = require('http-assert') //用于抛出错误
    const router = express.Router({
        mergeParams: true
    })
    const authMiddleware = require('../../middleware/auth')


    const resourceMiddleware = require('../../middleware/resource')
    router.post('/', async(req, res) => {
        const result = await req.Model.create(req.body)
        res.send({ code: 200, data: result, msg: '创建成功!' })
    })
    router.put('/:id', async(req, res) => {
        const result = await req.Model.findByIdAndUpdate(req.params.id, req.body)
        res.send({ code: 200, data: result, msg: '创建成功!' })
    })
    router.delete('/:id', async(req, res) => {
        const result = await req.Model.findByIdAndRemove(req.params.id)
        res.send({ success: true })
    })
    router.get('/', async(req, res) => {
        let data = {}
        const options = {}
        if (req.Model.modelName == 'Category') {
            data = await req.Model.find({}).populate('parent').limit(10)
        }
        if (req.Model.modelName == 'Article') {
            data = await req.Model.find({}).populate('categories').limit(10)
        } else {
            data = await req.Model.find({}).setOptions(options).limit(10)
        }
        res.send(data)
    })
    router.get('/:id', async(req, res) => {
        const model = await req.Model.findById(req.params.id)
        res.send(model)
    })
    app.use('/admin/api/rest/:resource', authMiddleware(), resourceMiddleware(), router)

    // multer 接收文件上传
    // 中间件
    const multer = require('multer')
    const uplod = multer({
        dest: __dirname + '/../../uploads'
    })
    app.post('/admin/api/upload', authMiddleware(), uplod.single('file'), async(req, res) => {
        const file = req.file
        file.url = `http://localhost:3000/uploads/${file.filename}`
        res.send(file)
    })

    app.post('/admin/api/login', async(req, res) => {
        const { username, password } = req.body
        const user = await model.findOne({ username }).select('+password')
        assert(user, 421, '用户名不存在！')
            // if (!user) {
            //     return res.status(401).send({ message: '用户名不存在！' })
            // }
            // 校验密码
        const isValid = require('bcrypt').compareSync(password, user.password)
        assert(isValid, 422, '密码错误!')
            // if (!isValid) {
            //     return res.status((402)).send({ message: '密码错误!' })
            // }
            // 3 返回token

        const token = jwt.sign({ id: user._id }, app.get('secret')) //get 获取全局配置
        res.send({ token })
    })
    app.use(async(err, req, res, next) => {
        res.status(err.statusCode || 500).send({
            message: err.message
        })
    })
}